# 通用部署脚本 - 自动检测环境
param(
    [string]$Environment = "auto",
    [string]$ProxyUrl = ""
)

Write-Host "🚀 AIDE 自动部署工具" -ForegroundColor Green
Write-Host ""

# 自动检测环境
if ($Environment -eq "auto") {
    if ($IsWindows -or $env:OS -like "*Windows*") {
        $Environment = "windows"
        Write-Host "🔍 检测到 Windows 环境" -ForegroundColor Yellow
    } else {
        $Environment = "linux"
        Write-Host "🔍 检测到 Linux 环境" -ForegroundColor Yellow
    }
} else {
    Write-Host "🎯 使用指定环境: $Environment" -ForegroundColor Yellow
}

# 设置配置文件
$ComposeFiles = @("-f", "docker-compose.prod.yml")
if ($Environment -eq "windows") {
    $ComposeFiles += @("-f", "docker-compose.windows.yml")
    Write-Host "📁 使用 Windows 配置" -ForegroundColor Cyan
} else {
    $ComposeFiles += @("-f", "docker-compose.linux.yml")
    Write-Host "📁 使用 Linux 配置" -ForegroundColor Cyan
}

# 检查环境变量文件
if (-not (Test-Path ".env.prod")) {
    Write-Host "⚠️ 警告：未找到 .env.prod 文件" -ForegroundColor Yellow
    Write-Host "请先创建 .env.prod 文件，参考 env-prod-template.txt" -ForegroundColor Yellow
    
    $continue = Read-Host "是否继续部署？(y/N)"
    if ($continue -ne "y" -and $continue -ne "Y") {
        Write-Host "❌ 部署已取消" -ForegroundColor Red
        exit 1
    }
}

# 设置代理（如果提供）
if ($ProxyUrl -ne "") {
    Write-Host "🔄 配置代理: $ProxyUrl" -ForegroundColor Yellow
    $env:HTTP_PROXY = $ProxyUrl
    $env:HTTPS_PROXY = $ProxyUrl
    $env:NO_PROXY = "localhost,127.0.0.1"
}

try {
    # 停止现有容器
    Write-Host "🛑 停止现有容器..." -ForegroundColor Yellow
    & docker-compose @ComposeFiles --env-file .env.prod down

    # 构建并启动服务
    Write-Host "🏗️ 构建并启动服务..." -ForegroundColor Green
    & docker-compose @ComposeFiles --env-file .env.prod up --build -d

    # 等待服务启动
    Write-Host "⏳ 等待服务启动..." -ForegroundColor Yellow
    Start-Sleep -Seconds 30

    # 检查服务状态
    Write-Host "🔍 检查服务状态..." -ForegroundColor Blue
    & docker-compose @ComposeFiles --env-file .env.prod ps

    Write-Host ""
    Write-Host "✅ 部署完成！" -ForegroundColor Green
    Write-Host "🌐 访问地址: http://localhost (Windows) 或 http://your-server-ip (Linux)" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "📊 常用命令:" -ForegroundColor Cyan
    Write-Host "  查看日志: docker-compose -f docker-compose.prod.yml -f docker-compose.$Environment.yml logs -f" -ForegroundColor White
    Write-Host "  重启服务: docker-compose -f docker-compose.prod.yml -f docker-compose.$Environment.yml restart" -ForegroundColor White
    Write-Host "  停止服务: docker-compose -f docker-compose.prod.yml -f docker-compose.$Environment.yml down" -ForegroundColor White

} catch {
    Write-Host "❌ 部署失败: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "请检查错误信息并重试" -ForegroundColor Yellow
    exit 1
}
